/********************************************************************************
* @File name: tty.c
* @Author: Loganx
* @Gitee: https://gitee.com/loganxiang/lgxsmartcar
* @Version: 1.0(2025-10-09)
* @Description: STC32G单片机串口终端
********************************************************************************
* 本软件使用了STC的STC32G官方库
********************************************************************************/
#include "Lib/Config.h"
#include "Lib/STC32G_GPIO.h"
#include "Lib/STC32G_UART.h"
#include "Lib/STC32G_NVIC.h"
#include "Lib/STC32G_Switch.h"
#include <string.h>
#include "tty.h"
#include "systick.h"

unsigned char *pTTYCmd;
unsigned char *pTTYArg[5];

unsigned char TTYsig,TTYInfork;
unsigned char TTYechot;

void TTYInit(void){
	GPIO_InitTypeDef gpio;
	COMx_InitDefine com1;
	
	gpio.Pin = GPIO_Pin_0|GPIO_Pin_1;
	gpio.Mode = GPIO_PullUp;
	
	GPIO_Inilize(GPIO_P3,&gpio);
	
	com1.UART_Mode = UART_8bit_BRTx;
	com1.UART_BRT_Use = BRT_Timer1;
	com1.UART_BaudRate = 115200ul;
	com1.UART_RxEnable = ENABLE;
	com1.BaudRateDouble = DISABLE;
	UART_Configuration(UART1,&com1);
	
	NVIC_UART1_Init(ENABLE,Priority_1);
	
	UART1_SW(UART1_SW_P30_P31);
}

//tty 字符回显函数
void TTYEchoString(char *str){
	printf(str);
}

//tty 数字回显函数
void TTYEchoNumber(char *str){
	int dig = atoi(str);
	
	printf("%hd",dig);
}

//tty 循环显示开机运行时间
void TTYEchoTime(void){
	TTYechot = TRUE;
	
	while(1){
		if(TTYsig == TRUE)
			if(strcmp(pTTYCmd,"exit") == 0){
				TTYechot = FALSE;
				break;
			}
	}
}

void TTYFork(void){
	TTYInfork = TRUE;
	
	if(TTYArgPhase() == FALSE)
		return;
	if(strcmp(pTTYCmd,"echos") == 0 && pTTYArg[0] != NULL){
		TTYEchoString(pTTYArg[0]);
	}
	
	if(strcmp(pTTYCmd,"echon") == 0 && pTTYArg[0] != NULL){
		TTYEchoNumber(pTTYArg[0]);
	}
	
	if(strcmp(pTTYCmd,"echot") == 0)
		TTYEchoTime();
	
	// TODO: 在此处添加用户代码
	
	TTYsig = FALSE;
	
	*pTTYCmd = NULL;		//目前由输入者确保参数正确性
	*pTTYArg[0] = NULL;
	*pTTYArg[1] = NULL;
	*pTTYArg[2] = NULL;
	*pTTYArg[3] = NULL;
	*pTTYArg[4] = NULL;
}

//tty 参数解析与分割
unsigned char TTYArgPhase(void){
	unsigned char i = 0;
	char *str = RX1_Buffer;
	
	if(*str == ' ' || *str == '\0')
		return FALSE;
	
	pTTYCmd = str;
	
	while(*str != '\0' || i > 4){
		str++;
		if(*str == ' '){
			*str = '\0';
			pTTYArg[i++] = ++str;
		}
	}
	return TRUE;
}

//UART1 systick callback(10ms)
//UART1 timeout reset RX_Cnt
void SystickCallbackUART1(void){
	if(--COM1.RX_TimeOut < 1){
		RX1_Buffer[COM1.RX_Cnt] = '\0';
		COM1.RX_Cnt = 0;
		TTYsig = TRUE;
	}
}

//Systick callback 500s
void SystickCallbackTTY(void){
	if(TTYsig == TRUE && TTYInfork == FALSE){
		TTYFork();
		TTYInfork = FALSE;
	}
}

//Systick callback 1s
void SystickCallbackTTYEchot(void){
	if(TTYechot == TRUE)
		printf("Running time(s):%ld",systick);
}